package com.kh.pajx.sop.view.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.base.SOPConfig;
import com.kh.pajx.sop.domain.HsSchoolInfo;
import com.kh.pajx.sop.domain.SysDepartment;
import com.kh.pajx.sop.domain.SysInsideUser;
import com.kh.pajx.sop.domain.SysUserGroup;
import com.kh.pajx.sop.domain.SysUserRole;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.FormatDate;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.security.encoder.DESSymmetricEncoderUtil;
import com.kh.pajx.sop.util.security.encoder.Md5PwdEncoderUtil;
import com.kh.pajx.sop.util.sop.PropertyValidate;
import com.opensymphony.xwork2.ActionContext;

/**
 * 内部用户信息Struts2控制器
 * @author:	azzcsimp
 * @Createdate:	2014年7月21日 上午9:50:00
 */
@Controller
@Scope("prototype")
public class SysInsideUserAction extends ModelDrivenBaseAction<SysInsideUser> {

	private static final long serialVersionUID = 2124593043824635774L;

	private HttpServletRequest request;

	/** 列表 */
	public String list() {
		
		try {
			// ============参数校验================
			validatePropertitysBySearch(model);
			
			
			
			setCSRFToken();

			// 准备用户组信息
			List<SysUserGroup> userGroupList = sysUserGroupService.findAll();
			ActionContext.getContext().put("userGroupList", userGroupList);
			// 准备用户角色信息
			List<SysUserRole> userRoleList = sysUserRoleService.findAll();
			ActionContext.getContext().put("userRoleList", userRoleList);

			// 此处主要是为了处理级联回显
			List<SysUserRole> userRoleListByGroup = new ArrayList<SysUserRole>();
			if (StringUtils.isNotEmpty(StringUtils.trim(model.getIsuGroupCode()))) {
				for (int i = 0; i < userRoleList.size(); i++) {
					if (userRoleList.get(i).getSysUserGroup().getUsgCode()
							.equals(StringUtils.trim(model.getIsuGroupCode()))) {
						userRoleListByGroup.add(userRoleList.get(i));
					}
				}
			}
			ActionContext.getContext().put("userRoleListByGroup", userRoleListByGroup);

			// 准备部门信息
			List<SysDepartment> departmentList = sysDepartmentService.getAll();
			ActionContext.getContext().put("departmentList", departmentList);

			new QueryHelper(SysInsideUser.class, "isu")
					//.addCondition("isu.isuStatusFlag=?", 1)
					.addCondition("isu.account!=?", "SuperAdmin")
					.addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getIsuName())),
							"isu.isuName like ? or isu.isuPhone=?", "%" + StringUtils.trim(model.getIsuName()) + "%",
							StringUtils.trim(model.getIsuName()))
					// 查询参数1用户名
					.addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getIsuGroupCode())), "isu.isuGroupCode=?",
							StringUtils.trim(model.getIsuGroupCode()))
					// 查询参数2用户组
					.addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getIsuRoleCode())), "isu.isuRoleCode=?",
							StringUtils.trim(model.getIsuRoleCode()))
					// 查询参数3用户角色
					.addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getDeptCode())), "isu.deptCode=?",
							StringUtils.trim(model.getDeptCode())) // 查询参数4部门
					.preparePageBean(sysInsideUserService, pageNum, numPerPage);
		} catch (Exception e) {
			e.printStackTrace();
			ActionContext.getContext().put("errorMsg", "检索失败！"+e.getMessage());
		}
		return "list";
	}

	/** 添加页面 */
	public String addUI() {
		setCSRFToken();
		// 准备部门信息
		List<SysDepartment> departmentList = sysDepartmentService.getAll();
		ActionContext.getContext().put("departmentList", departmentList);

		// 准备用户组信息
		List<SysUserGroup> userGroupList = sysUserGroupService.findAll();
		ActionContext.getContext().put("userGroupList", userGroupList);
		return "addUI";
	}

	/** 添加 */
	public void add() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		if(checkCSRFToken()){
			try {
				
				model.setIsuName(StringUtils.trim(model.getIsuName()));
				model.setIsuPhone(StringUtils.trim(model.getIsuPhone()));
				model.setIsuIMEI(StringUtils.trim(model.getIsuIMEI()));
				model.setIsuEmail(StringUtils.trim(model.getIsuEmail()));
				model.setRemark(StringUtils.trim(model.getRemark()));
				model.setAccount(model.getIsuPhone());
				if(SOPConfig.CODE_USER_ROLE_EXTEND.equals(model.getIsuRoleCode())){
					model.setManagerFlag(model.getManagerFlag());
				}else{
					model.setManagerFlag("0");
				}
				model.setPassword(Md5PwdEncoderUtil.encrytion("00000000"));
				model.setIsuStatusFlag(1);
				model.setCreateTime(FormatDate.dateTimeDetail());
				model.setCreateOperId(getCurrentUser().getUserId());
				
				
				validatePropertitysByAdd(model);//安全验证
				if (sysInsideUserService.checkPhone(model.getIsuPhone(), model.getIsuId())) {
					sysInsideUserService.save(model);
					dwz.setMessage("保存成功！");
					dwz.setCallbackType("closeCurrent");
					dwz.setNavTabId("insideUser_list");
					dwz.setStatusCode("200");
					DwzAjaxResult.josnMessage(dwz);
				} else {
					dwz.setMessage("保存失败！<br>手机号已存在！");
					dwz.setStatusCode("300");
					DwzAjaxResult.josnMessage(dwz);
				}

			} catch (Exception e) {
				e.printStackTrace();
				dwz.setMessage("保存失败！<br>错误信息：" + e.getMessage());
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
			}
		} else {
			dwz.setStatusCode("300");
			dwz.setMessage("未授权非法操作，身份认证失败！");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 修改页面 */
	public String editUI() {
		setCSRFToken();
		// 准备部门信息
		List<SysDepartment> departmentList = sysDepartmentService.getAll();
		ActionContext.getContext().put("departmentList", departmentList);

		// 准备用户组信息
		List<SysUserGroup> userGroupList = sysUserGroupService.findAll();
		ActionContext.getContext().put("userGroupList", userGroupList);

		// 准备用户信息
		SysInsideUser insideUser = sysInsideUserService.getById(StringUtils.trim(model.getIsuId()));
		ActionContext.getContext().getValueStack().push(insideUser);
		// 准备用户角色信息
		List<SysUserRole> userRoleList = sysUserRoleService.findAll();
		ActionContext.getContext().put("userRoleList", userRoleList);

		// 此处主要是为了处理级联回显
		List<SysUserRole> userRoleListByGroup = new ArrayList<SysUserRole>();
		if (StringUtils.isNotEmpty(StringUtils.trim(insideUser.getIsuGroupCode()))) {
			for (int i = 0; i < userRoleList.size(); i++) {
				if (userRoleList.get(i).getSysUserGroup().getUsgCode()
						.equals(StringUtils.trim(insideUser.getIsuGroupCode()))) {
					userRoleListByGroup.add(userRoleList.get(i));
				}
			}
		}
		ActionContext.getContext().put("userRoleListByGroup", userRoleListByGroup);
		return "editUI";
	}

	/** 修改 */
	public void edit() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		if(checkCSRFToken()){
			try {
				SysInsideUser insideUser = sysInsideUserService.getById(StringUtils.trim(model.getIsuId()));
				insideUser.setIsuGroupCode(model.getIsuGroupCode());
				insideUser.setIsuRoleCode(model.getIsuRoleCode());
				insideUser.setDeptCode(model.getDeptCode());
				insideUser.setIsuSex(model.getIsuSex());
				if(SOPConfig.CODE_USER_ROLE_EXTEND.equals(model.getIsuRoleCode())){
					insideUser.setManagerFlag(model.getManagerFlag());
				}else{
					insideUser.setManagerFlag("0");
				}
				insideUser.setIsuName(StringUtils.trim(model.getIsuName()));
				insideUser.setIsuPhone(StringUtils.trim(model.getIsuPhone()));
				insideUser.setAccount(StringUtils.trim(model.getIsuPhone()));
				insideUser.setIsuIMEI(StringUtils.trim(model.getIsuIMEI()));
				insideUser.setIsuEmail(StringUtils.trim(model.getIsuEmail()));
				insideUser.setRemark(StringUtils.trim(model.getRemark()));
				
				validatePropertitysByUpdate(insideUser);//安全验证
				if (sysInsideUserService.checkPhone(model.getIsuPhone(), model.getIsuId())) {
					sysInsideUserService.update(insideUser);
					dwz.setMessage("修改成功！");
					dwz.setCallbackType("closeCurrent");
					dwz.setNavTabId("insideUser_list");
					dwz.setStatusCode("200");
					DwzAjaxResult.josnMessage(dwz);
				} else {
					dwz.setMessage("保存失败！<br>手机号已存在！");
					dwz.setStatusCode("300");
					DwzAjaxResult.josnMessage(dwz);
				}
			} catch (Exception e) {
				e.printStackTrace();
				dwz.setMessage("修改失败！<br>错误信息：" + e.getMessage());
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
			}
		} else {
			dwz.setStatusCode("300");
			dwz.setMessage("未授权非法操作，身份认证失败！");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 更改状态 */
	public void updateFlag() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		if(checkCSRFToken()){
			try {
				if(!ValidatorUtils.validateUUID(model.getIsuId(),false)){
		    		throw new Exception("属性[用户编号]输入错误，非法提交！");
		    	}
				SysInsideUser insideUser = sysInsideUserService.getById(model.getIsuId());
				dwz.setMessage("已成功" + (insideUser.getIsuStatusFlag() == 1 ? "停用" : "启用") + "用户<font color='red'>"
						+ insideUser.getIsuName() + "</font>!");
				insideUser.setIsuStatusFlag(insideUser.getIsuStatusFlag() == 1 ? 0 : 1);
				sysInsideUserService.update(insideUser);
				dwz.setNavTabId("insideUser_list");
				dwz.setStatusCode("200");
				DwzAjaxResult.josnMessage(dwz);
			} catch (Exception e) {
				e.printStackTrace();
				dwz.setStatusCode("300");
				dwz.setMessage("设置失败！错误原因："+e.getMessage());
				DwzAjaxResult.josnMessage(dwz);
			}
		} else {
			dwz.setStatusCode("300");
			dwz.setMessage("未授权非法操作，身份认证失败！");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 删除  关闭物理删除，避免出现用户信息被删除历史操作人记录里找不到对应人员信息
	 * 如果删除可以设置停用即可
	public void delete() {
		// TODO: 判断有无数据需要处理
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			sysInsideUserService.delete(model.getIsuId());
			dwz.setMessage("删除成功!");
			dwz.setNavTabId("insideUser_list");
			dwz.setStatusCode("200");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("删除失败!<br>错误信息：" + e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	} */

	/** 查看 */
	public String show() {
	    DwzAjaxResult dwz = new DwzAjaxResult();
		try {
		    if (checkCSRFToken()) {
		    	if(!ValidatorUtils.validateUUID(model.getIsuId(),false)){
		    		throw new Exception("属性[用户编号]输入错误，非法提交！");
		    	}
			// 准备用户信息
			SysInsideUser insideUser = sysInsideUserService.getById(StringUtils.trim(model.getIsuId()));
			ActionContext.getContext().getValueStack().push(insideUser);
			return "show";
		    } else {
			return NOTOKEN;
		    }
		} catch (Exception e) {
		    dwz.setStatusCode("300");
		    dwz.setConfirmMsg("查询错误" + e.getMessage());
		    DwzAjaxResult.josnMessage(dwz);
		    return null;
		}
	}

	/** 密码重置 */
	public void resetPwd() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		if(checkCSRFToken()){
			try {
				if(!ValidatorUtils.validateUUID(model.getIsuId(),false)){
		    		throw new Exception("属性[用户编号]输入错误，非法提交！");
		    	}
				SysInsideUser insideUser = sysInsideUserService.getById(StringUtils.trim(model.getIsuId()));
				insideUser.setPassword(Md5PwdEncoderUtil.encrytion("00000000"));
				sysInsideUserService.update(insideUser);
				dwz.setMessage("密码重置成功!");
				//dwz.setNavTabId("insideUser_list");
				dwz.setStatusCode("200");
				DwzAjaxResult.josnMessage(dwz);
			} catch (Exception e) {
				e.printStackTrace();
				dwz.setMessage("密码重置失败!<br>错误信息：" + e.getMessage());
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
			}
		} else {
			dwz.setStatusCode("300");
			dwz.setMessage("未授权非法操作，身份认证失败！");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 修改密码页面 */
	public String changePwdUI() {
		setCSRFToken();
		return "changePwdUI";
	}

	/** 修改密码 */
	public void changePwd() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		if (checkCSRFToken()) {
			try {
				DESSymmetricEncoderUtil des = new DESSymmetricEncoderUtil();
				HttpServletRequest request = ServletActionContext.getRequest();
				String oldPassword = des.decrypt(request.getParameter("oldPassword"), getCSRFToken(), "SOP", "LOGIN");
				String newPassword = des.decrypt(request.getParameter("newPassword"), getCSRFToken(), "SOP", "LOGIN");
				String rnewPassword = des.decrypt(request.getParameter("rnewPassword"), getCSRFToken(), "SOP", "LOGIN");
				SysInsideUser insideUser = getCurrentUser().getInsideUser();
				if (!insideUser.getPassword().equals(Md5PwdEncoderUtil.encrytion(oldPassword))) {
					dwz.setMessage("密码修改失败!<br>错误信息：旧密码输入错误！");
					dwz.setStatusCode("300");
					DwzAjaxResult.josnMessage(dwz);
				} else if (!newPassword.equals(rnewPassword)) {
					dwz.setMessage("密码修改失败!<br>错误信息：新密码前后输入不一致！");
					dwz.setStatusCode("300");
					DwzAjaxResult.josnMessage(dwz);
				} else {
					insideUser.setPassword(Md5PwdEncoderUtil.encrytion(rnewPassword));
					sysInsideUserService.update(insideUser);
					dwz.setMessage("密码修改成功!");
					dwz.setCallbackType("closeCurrent");
					dwz.setStatusCode("200");
					DwzAjaxResult.josnMessage(dwz);
				}

			} catch (Exception e) {
				e.printStackTrace();
				dwz.setMessage("密码修改失败!<br>错误信息：" + e.getMessage());
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
			}
		} else {
			dwz.setStatusCode("300");
			dwz.setMessage("未授权非法操作，身份认证失败！");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	public void checkPhone() {
		PrintWriter out = null;
		request = ServletActionContext.getRequest();
		String insideUserId = request.getParameter("InsideuserId");
		try {
			if(!ValidatorUtils.validateUUID(insideUserId,false)){
	    		throw new Exception("属性[用户编号]输入错误，非法提交！");
	    	}
			if(!ValidatorUtils.validatePhone(model.getIsuPhone(),false)){
	    		throw new Exception("属性[电话号码]输入错误，非法提交！");
	    	}
			out = ServletActionContext.getResponse().getWriter();
			if (sysInsideUserService.checkPhone(model.getIsuPhone(), insideUserId)) {
				out.write("true");
			} else {
				out.write("false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	public void checkPhoneForAdd() {
		PrintWriter out = null;
		request = ServletActionContext.getRequest();
		try {
			if(!ValidatorUtils.validatePhone(model.getIsuPhone(),false)){
	    		throw new Exception("属性[电话号码]输入错误，非法提交！");
	    	}
			out = ServletActionContext.getResponse().getWriter();
			if (sysInsideUserService.checkPhone(model.getIsuPhone())) {
				out.write("true");
			} else {
				out.write("false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	
	/**安全验证*/
	private void validatePropertitysBySearch(SysInsideUser demo)throws Exception{
    	if(!ValidatorUtils.validateRelativeSafeString(demo.getIsuName(),20, true)){
    		throw new Exception("属性[姓名或手机号]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuGroupCode(), 4, true)){
    		throw new Exception("属性[用户组编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuRoleCode(), 4, true)){
    		throw new Exception("属性[角色编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getDeptCode(), 4, true)){
    		throw new Exception("属性[部门编码]输入错误，非法提交！");
    	}
    }
	private void validatePropertitysByAdd(SysInsideUser demo)throws Exception{
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuGroupCode(),4, false)){
    		throw new Exception("属性[用户组编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuRoleCode(), 4, false)){
    		throw new Exception("属性[角色编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getDeptCode(), 4, false)){
    		throw new Exception("属性[部门编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateRelativeSafeString(demo.getIsuName(),20, true)){
    		throw new Exception("属性[姓名]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuSex(), 1, false)){
    		throw new Exception("属性[性别]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getManagerFlag(), 1, true)){
    		throw new Exception("属性[大区经理标识]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validatePhone(demo.getIsuPhone(), false)){
    		throw new Exception("属性[手机号码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuIMEI(), 15, true)){
    		throw new Exception("属性[手机串号]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateEmail(demo.getIsuEmail(),false)){
    		throw new Exception("属性[电子邮箱]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateRelativeSafeString(demo.getRemark(), 200, true)){
    		throw new Exception("属性[备注信息]输入错误，非法提交！");
    	}
    }
	
	private void validatePropertitysByUpdate(SysInsideUser demo)throws Exception{
		if(!ValidatorUtils.validateUUID(demo.getIsuId(),false)){
    		throw new Exception("属性[用户编号]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuGroupCode(),4, false)){
    		throw new Exception("属性[用户组编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuRoleCode(), 4, false)){
    		throw new Exception("属性[角色编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getDeptCode(), 4, false)){
    		throw new Exception("属性[部门编码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateRelativeSafeString(demo.getIsuName(),20, true)){
    		throw new Exception("属性[姓名]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuSex(), 1, false)){
    		throw new Exception("属性[性别]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getManagerFlag(), 1, true)){
    		throw new Exception("属性[大区经理标识]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validatePhone(demo.getIsuPhone(), false)){
    		throw new Exception("属性[手机号码]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getIsuIMEI(), 15, true)){
    		throw new Exception("属性[手机串号]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateEmail(demo.getIsuEmail(),false)){
    		throw new Exception("属性[电子邮箱]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateRelativeSafeString(demo.getRemark(), 200, true)){
    		throw new Exception("属性[备注信息]输入错误，非法提交！");
    	}
    }

}
